package com.start.shop.modules.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.start.shop.api.vo.order.OrderAddress;
import com.start.shop.common.constant.RspCode;
import com.start.shop.common.constant.SysConstants;
import com.start.shop.common.constant.TableFeildCode;
import com.start.shop.common.exception.MyException;
import com.start.shop.common.util.Snowflake;
import com.start.shop.modules.repository.dao.OrderDao;
import com.start.shop.modules.repository.entity.CouponConfig;
import com.start.shop.modules.repository.entity.Goods;
import com.start.shop.modules.repository.entity.Order;
import com.start.shop.modules.repository.entity.Sku;
import com.start.shop.modules.repository.entity.SkuAttr;
import com.start.shop.modules.service.ICouponService;
import com.start.shop.modules.service.IGoodsService;
import com.start.shop.modules.service.IOrderService;
import com.start.shop.modules.service.ISkuService;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service
public class OrderServiceImpl implements IOrderService {
		
	@Autowired
	OrderDao orderDao;
	
	@Autowired
    private Snowflake snowflake;

	@Autowired
	IGoodsService goodsService;
	
	@Autowired
	ISkuService skuService;
	
	@Autowired
	ICouponService couponService;
	
	

	/**
	 * 订单创建
	 */
	@Override
	@Transactional
	public Order make(int userId, int skuId, int num, int couponId, String orderChannel, OrderAddress orderAddress, int agentId) {
		
		//创建order对象
		Order order = new Order();
		//扣减库存
		if(!skuService.stockOut(skuId, num)) {
			//扣减库存失败
			throw new MyException(RspCode.GOODS_STOCK_NOT_ENOUGH);
		}
		//获取sku的产品信息
		Sku sku = skuService.getSkuBySkuId(skuId);
		//获取商品属性
		SkuAttr skuAttr = skuService.getSkuAttrById(skuId);
		//获取商品编号
		Goods goods = goodsService.getGoodsByGoodsId(sku.getGoodsId());
		//设置订单-商品信息
		order.setOrderChannel(orderChannel);
		order.setGoodsId(goods.getGoodsId());
		order.setGoodsName(goods.getGoodsName());
		order.setGoodsType(goods.getGoodsType());
		order.setSkuId(skuId);
		order.setSkuImg(sku.getSkuImg());
		order.setSkuAttr(null);
		order.setSkuPrice(sku.getSkuPrice());
		order.setBuyCnt(num);
		order.setAgentId(agentId);
		
		//计算价格
		BigDecimal totalAmt = sku.getSkuPrice().multiply(new BigDecimal(num));
		//设置订单-价格
		order.setTotalAmt(totalAmt);
		 
		//产生订单号
		String orderNo = String.valueOf(snowflake.nextId());
		order.setOrderNo(orderNo);
		
		//设置地址
		order.setPostName(orderAddress.getPostName());
		order.setPostMobile(orderAddress.getPostMobile());
		order.setPostAddress(orderAddress.getAddress());
		//使用优惠券
		BigDecimal actualAmt;
        actualAmt = null;
        //核销优惠券
        if(couponId > 0) {
        	CouponConfig couponConfig = couponService.writeOffCoupon(userId, couponId, totalAmt, goods.getGoodsId(), goods.getGoodsType());
			actualAmt = totalAmt.subtract(couponConfig.getCutAmt()); //实际支付金额
			order.setCouponId(couponId);
			order.setCouponAmt(couponConfig.getCutAmt());
			order.setCouponName(couponConfig.getCouponName());
			order.setCouponDesc(couponConfig.getCouponDesc());
		}
		else {
			actualAmt = totalAmt;
		}
		order.setActualAmt(actualAmt);
		
		
		//订单状态和客户信息
		order.setOrderStatus(TableFeildCode.T_ORDER_STATUS_CREATE.getCode());
		order.setPayStatus(TableFeildCode.T_ORDER_PAY_STATUS_NOTPAY.getCode());
		order.setCreateTime(new Date());
		order.setUserId(userId);
		
		//插入订单
		orderDao.insert(order);
		
		return order;
	}
	

	/**
	 * 获取指定订单信息
	 */
	@Override
	public Order getOrderByOrderNo( int userId, String orderNo) {
		return orderDao.selectOrderByOrderNo( userId, orderNo);
	}
	
	/**
	 * 订单更新未支付订单为支付中
	 */
	@Override
	public void orderPayCheck(int userId, String orderNo) {
		//将已创建未支付的订单更新为处理中和支付中
		int count = orderDao.updatePayStatusToPaying(userId, orderNo);
		if(count != 1) {
			log.error("该订单状态为不可以进行支付,订单信息号：【{}】 客户编号【{}】,count【{}】", orderNo, userId, count);
			throw new MyException(RspCode.ORDER_CANNOT_PAY.getCode(), RspCode.ORDER_CANNOT_PAY.getMessage());
		}
	}
	
	
	/**
	 * 订单支付成功  - 将支付状态更新为已支付, 订单状态更新为已受理
	 * 支付状态 03-已支付  订单状态 03-已受理 
	 */
	@Override
	public void orderPaySuccess(int userId, String orderNo, String payNo) {	
		int i = orderDao.updatePayingToSuccess(userId, orderNo, payNo);
		if (i != 1) {
			log.error("支付成功后更新订单状态失败,订单信息号：【{}】payNo【{}】custId【{}】 ", orderNo, payNo, userId);
			throw new MyException(RspCode.ORDER_CANNOT_PAY.getCode(), RspCode.ORDER_CANNOT_PAY.getMessage());
		}
	}
	
	/**
	 * 订单取消
	 */
	@Override
	public int orderCancel(int userId, String orderNo) {
		//查询order
		Order order = orderDao.selectOrderByOrderNo(userId, orderNo);
		if (order == null) {
			throw new MyException(RspCode.ORDER_NOT_FOUND);
		}
		//释放库存
		skuService.stockIn(order.getSkuId(), order.getBuyCnt());
		//取消订单
		return orderDao.updateOrderToCancel(userId, orderNo);
	}
	
	/**
	 * 订单发货
	 */
	@Override
	public void orderDelivery(int userId, String orderNo, String deliveryNo) {
		orderDao.updateDelivery(userId, orderNo, deliveryNo);
	}
	
	
	/**
	 * 订单确认
	 */
	@Override
	public void orderConfirm(int userId, String orderNo) {
		orderDao.updateOrderConfirm(userId, orderNo);
	}

	
	/**
	 * 根据订单状态查询订单
	 */
	@Override
	public PageInfo<Order> getOrderByStatus(int userId, String orderStatus, String payStatus, int pageNum, int pageSize, String orderChannel) {
		
	    //创建页面对象
        PageHelper.startPage(pageNum, pageSize);
     
        List<Order> orderList = orderDao.selectOrderByStatus(userId, orderStatus, payStatus, orderChannel);
		//生成页面信息
        
		return new PageInfo<Order>(orderList);
	}

	/**
	 * 批量关闭已过期的订单
	 */
	@Override
	public void orderCancelBat() {
		List<Order> orderList= orderDao.selectExpireOrder();
		while(orderList.size() !=0) {
			for (Order order : orderList) {
				//取消订单
				orderCancel(order.getUserId(), order.getOrderNo());
			}
			orderList= orderDao.selectExpireOrder();
		}
	}
	
	
	/**
	 * 批量确认已过期的订单
	 */
	@Override
	public void orderConfirmBat() {
		List<Order> orderList =orderDao.selectConfirmOrder();
		while(orderList.size() != 0) {
			//确认订单
			for (Order order : orderList) {
				orderConfirm( order.getUserId(), order.getOrderNo());
			}
			orderList =orderDao.selectConfirmOrder();
		}
	}


}
